const schedule = require("node-schedule");
const axios = require("axios");
const puppeteer = require("puppeteer-core");

const { getResult } = require("../utils/sql");

const headers = {
  "User-Agent":
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36",
};

// 当下所有最新的表 先清空数据(若已有)
async function deleteList(type) {
  return new Promise(async (resolve) => {
    let sql = `DELETE FROM platform_hot_today_list WHERE platform_flag=? AND date=?`;
    let paramsList = [type, new Date().toISOString().split("T")[0]];
    await getResult({ sql, paramsList });
    resolve();
  });
}

async function insertList(list) {
  let addPromises = list.map((item, index) => {
    return new Promise(async (resolve) => {
      let sql = `INSERT INTO platform_hot_today_list (title,hot_num,url,platform_flag,date,rank) value(?,?,?,?,?,?)`;
      let paramsList = [
        item.title,
        item.num,
        item.url,
        item.platform_flag,
        item.date,
        index,
      ];

      await getResult({ sql, paramsList });
      resolve();
    });
  });

  Promise.all(addPromises);
}

async function getHupuHotList() {
  deleteList(7);

  const browser = await puppeteer.launch({
    headless: true,
    args: ["--no-sandbox", "--disable-setuid-sandbox"],
    executablePath:
      "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
  });

  const page = await browser.newPage();
  await page.goto("https://bbs.hupu.com/all-gambia");

  var posts = await page.evaluate(() => {
    return Array.from(document.querySelectorAll(".list-item-wrap")).map(
      (post) => ({
        title: post.querySelector(".t-title")?.innerText.trim(),
        num: post.querySelector(".t-lights")?.innerText.trim().slice(0, -1),
        url: post.querySelector("a")?.href,
        platform_flag: 7,
        date: new Date().toISOString().split("T")[0],
      })
    );
  });

  posts = posts.filter((item) => item.title);
  console.log(posts, "=====getHupuHotList");

  insertList(posts);
}

// 先浏览器模拟 失败再使用puppeteer
async function getZhihuHot() {
  deleteList(1);
  try {
    const res = await axios.get(
      "https://www.zhihu.com/api/v3/feed/topstory/hot-lists/total?limit=50&desktop=true",
      {
        headers: {
          ...headers,
          Referer: "https://www.zhihu.com/hot",
        },
      }
    );

    if (res.status === 200 && res.data && res.data.data) {
      let hotList = res.data.data.map((item) => ({
        title: item.target.title,
        num: item.detail_text,
        url: `https://www.zhihu.com/question/${item.card_id.slice(2)}`,
        date: new Date().toISOString().split("T")[0],
        platform_flag: 1,
      }));

      insertList(hotList);
    }
  } catch (error) {
    console.log(error, "数据获取失败:", error.message);
    const browser = await puppeteer.launch({
      headless: true,
      args: [
        "--no-sandbox",
        "--disable-setuid-sandbox",
        "--disable-web-security",
        "--disable-features=IsolateOrigins,site-per-process",
        "--window-size=1920,1080",
      ],
      executablePath:
        "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
    });
    const page = await browser.newPage();
    await page.goto("https://www.zhihu.com/hot");
    const tops = await page.evaluate(() => {
      console.log(Array.from(document.querySelectorAll(".HotItem")), "====108");
      return Array.from(document.querySelectorAll(".HotItem")).map((hot) => ({
        title: hot.querySelector(".HotItem-title")?.innerText.trim(),
        num: hot.querySelector(".HotItem-metrics")?.innerText.trim(),
        url: hot.querySelector("a")?.href,
        date: new Date().toISOString().split("T")[0],
        platform_flag: 1,
      }));
    });
    insertList(tops);
    console.log(tops, " =====118");
  }
}

async function getWeiboHot() {
  deleteList(3);
  try {
    const res = await axios.get(" https://weibo.com/ajax/side/hotSearch", {
      headers: {
        ...headers,
        Referer: "https://www.weibo.com/hot/search",
      },
    });

    let hotList = res.data.data.realtime.map((item) => ({
      title: item.word,
      num: item.num,
      date: new Date().toISOString().split("T")[0],
      platform_flag: 3,
      url: `https://s.weibo.com/weibo?q=${item.word}`,
    }));

    insertList(hotList);
  } catch (error) {
    console.log(error, "数据获取失败:", error.message);
    const browser = await puppeteer.launch({
      headless: true,
      args: ["--no-sandbox", "--disable-setuid-sandbox"],
    });
    const page = await browser.newPage();
    await page.goto("https://www.zhihu.com/hot");
    const tops = await page.evaluate(() => {
      return Array.from(document.querySelectorAll(".trend-topic-item")).map(
        (post) => ({
          title: post.querySelector("a")?.innerText.trim(),
          num: post.querySelector(".trend-score")?.innerText.trim(),
          url: post.querySelector("a")?.href,
          date: new Date().toISOString().split("T")[0],
          platform_flag: 4,
        })
      );
    });

    insertList(tops);
  }
}

async function getJueJinHot() {
  deleteList(2);

  try {
    const res = await axios.get(
      "https://api.juejin.cn/content_api/v1/content/article_rank?category_id=1&type=hot&aid=2608&uuid=7293822382472201737&spider=0",
      {
        headers: {
          ...headers,
          Referer: "https://juejin.cn/",
        },
      }
    );

    let hotList = res.data.data.map((item) => ({
      title: item.content.title,
      num: item.content_counter.hot_rank,
      date: new Date().toISOString().split("T")[0],
      platform_flag: 2,
      url: `https://juejin.cn/post/${item.content.content_id}`,
    }));

    insertList(hotList);
  } catch (error) {
    console.log(error, "数据获取失败:", error.message);

    return [];
  }
}

async function getDoubanHot() {
  deleteList(4);
  const browser = await puppeteer.launch({
    headless: true,
    args: ["--no-sandbox", "--disable-setuid-sandbox"],
    executablePath:
      "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
  });

  const page = await browser.newPage();
  await page.goto("https://www.douban.com/gallery/");
  const tops = await page.evaluate(() => {
    return Array.from(document.querySelectorAll(".trend-topic-item")).map(
      (post) => ({
        title: post.querySelector("a")?.innerText.trim(),
        num: post.querySelector(".trend-score")?.innerText.trim(),
        url: post.querySelector("a")?.href,
        date: new Date().toISOString().split("T")[0],
        platform_flag: 4,
      })
    );
  });

  insertList(tops);
}

async function getBaiduList() {
  deleteList(5).then(async () => {
    const browser = await puppeteer.launch({
      headless: true,
      args: ["--no-sandbox", "--disable-setuid-sandbox"],
      executablePath:
        "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
    });

    const page = await browser.newPage();
    await page.goto("https://www.baidu.com");

    const hots = await page.evaluate(() => {
      return Array.from(document.querySelectorAll(".hotsearch-item")).map(
        (hot) => ({
          title: hot.querySelector(".title-content-title")?.innerText.trim(),
          url: hot.querySelector("a")?.href,
          date: new Date().toISOString().split("T")[0],
          platform_flag: 5,
          num: 0,
        })
      );
    });

    console.log(hots, "=====248");
    insertList(hots);
  });
}

async function getBilibiliList() {
  deleteList(6).then(async () => {
    const browser = await puppeteer.launch({
      headless: true,
      args: [
        "--no-sandbox",
        "--disable-setuid-sandbox",
        "--disable-web-security",
        "--disable-features=IsolateOrigins,site-per-process",
        "--window-size=1920,1080",
      ],
      executablePath:
        "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
    });

    const page = await browser.newPage();
    await page.goto("https://www.bilibili.com/v/popular/all");

    const hots = await page.evaluate(() => {
      return Array.from(document.querySelectorAll(".video-card")).map(
        (hot) => ({
          title: hot.querySelector(".video-name")?.innerText.trim(),
          num: hot.querySelector(".play-text")?.innerText.trim(),
          url: hot.querySelector(".video-card__content a")?.href,
          platform_flag: 6,
          date: new Date().toISOString().split("T")[0],
        })
      );
    });

    console.log(hots, "=====273");

    insertList(hots);
  });
}
async function getHotList() {
  await getHupuHotList();
  await getZhihuHot();
  await getWeiboHot();
  await getJueJinHot();
  await getDoubanHot();
  await getBilibiliList();
  await getBaiduList();
}

// 每个小时都执行
schedule.scheduleJob("0 0 * * * *", async () => {
  console.log("定时任务开始执行");
  await getHotList();
  console.log("定时任务执行完毕");
});

module.exports = {
  getHupuHotList,
  getZhihuHot,
  getWeiboHot,
  getJueJinHot,
  getDoubanHot,
  getBilibiliList,
  getBaiduList,
  getHotList,
};
